from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.parsers import JSONParser
import os
import ctypes
from django.conf import settings

class _MD5(APIView):
    parser_classes = [JSONParser]
    def post(self, request):
        try:
            plaintext = request.data.get('plaintext', '').encode('utf-8')
            lib_path = os.path.join(settings.BASE_DIR, 'api', 'dll', 'main.dylib')
            # 加载动态链接库
            lib = ctypes.CDLL(lib_path)  # 替换成实际的库文件名和路径
            # 定义C函数的参数类型
            lib._MD5.argtypes = [ctypes.c_char_p, ctypes.c_size_t]
            # 定义C函数的返回类型
            lib._MD5.restype = ctypes.c_char_p
            return Response({
                'hash': lib._MD5(plaintext, len(plaintext)).decode('utf-8')
            })
        except Exception as e:
            return Response({
                'error': str(e)
            })